﻿Imports Microsoft.VisualBasic
Imports Microsoft.VisualBasic.CompilerServices
Imports System
Imports System.ComponentModel
Imports System.Diagnostics
Imports System.Drawing
Imports System.IO
Imports System.Resources
Imports System.Windows.Forms

Public Class Form1
    Dim exeCollection As New List(Of String)
    Dim isCanceled As Boolean
    Dim destinationFolder As String = ""
    Dim dots As String = Chr(133)
    Dim helpText As String

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Me.DoubleBuffered = True
        Me.Text = "Bundle LÖVE - " & My.Application.Info.Version.ToString
        LoveFolderBTN.Text = dots
        programFolderBTN.Text = dots
        programiconBTN.Text = dots
        destinationBTN.Text = dots

        helpText = logTB.Text
        logTB.Text = ""
        mess("Ready.")

        destinationTB.Text = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) & "\"

        If File.Exists("C:\Program Files (x86)\LOVE\love.exe") Then
            loveFolderTB.Text = "C:\Program Files (x86)\LOVE\"
        ElseIf File.Exists("C:\Program Files\LOVE\love.exe") Then
            loveFolderTB.Text = "C:\Program Files\LOVE\"
        End If

        If loveFolderTB.Text = "" Then
            mess("LÖVE program path not found. Please browse to find program folder.")
            HighLight(loveFolderTB, True)
        End If

        PictureBox1.Select()

    End Sub
    Private Sub HighLight(ByRef tb As Object, highlight As Boolean)
        If highlight = True Then
            tb.BackColor = Color.PaleTurquoise
        Else
            tb.BackColor = SystemColors.Window
        End If
    End Sub
    Private Sub LoveFolderBTN_Click(sender As System.Object, e As System.EventArgs) Handles LoveFolderBTN.Click
        pb.Value = 0
        FolderBrowserDialog1.ShowNewFolderButton = False
        FolderBrowserDialog1.Description = "Select the LÖVE program folder"

        If (Me.FolderBrowserDialog1.ShowDialog() = DialogResult.OK) Then
            If File.Exists(FolderBrowserDialog1.SelectedPath & "\love.exe") = True Then
                loveFolderTB.Text = FolderBrowserDialog1.SelectedPath & "\"
                HighLight(loveFolderTB, False)
                mess("LÖVE program path: " & loveFolderTB.Text)
            Else
                HighLight(loveFolderTB, True)
                mess("LÖVE program path not found. Please browse to find program folder.")
            End If
        End If
    End Sub

    Private Sub programFolderBTN_Click(sender As System.Object, e As System.EventArgs) Handles programFolderBTN.Click
        pb.Value = 0
        FolderBrowserDialog1.ShowNewFolderButton = False
        FolderBrowserDialog1.Description = "Select the program folder"

        If (Me.FolderBrowserDialog1.ShowDialog() = DialogResult.OK) Then
            HighLight(programFolderTB, False)
            autorunsCB.Items.Clear()
            autorunsCB.ResetText()
            exeCollection.Clear()
            getDirectoyExe(Me.FolderBrowserDialog1.SelectedPath)

            If (autorunsCB.Items.Count > 0) Then
                autorunsCB.SelectedIndex = 0
                Call autorunsCB_SelectedIndexChanged(Nothing, Nothing)
            End If
            programFolderTB.Text = Me.FolderBrowserDialog1.SelectedPath
        End If
    End Sub

    Private Sub autorunsCB_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles autorunsCB.SelectedIndexChanged
        pb.Value = 0
        HighLight(autorunsCB, False)
        If (autorunsCB.SelectedItem.ToLower.EndsWith(".exe")) Then
            destinationTB.Text = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) & "\" & autorunsCB.SelectedItem
        Else
            destinationTB.Text = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) & "\" & autorunsCB.SelectedItem & ".exe"
        End If
        mess("Program folder selected: " & destinationTB.Text)
    End Sub
    Public Sub getDirectoyExe(ByVal startFolder As String)
        Dim directories As DirectoryInfo() = (New DirectoryInfo(startFolder)).GetDirectories()
        Dim files As System.IO.FileInfo() = (New DirectoryInfo(startFolder)).GetFiles()
        Dim num As Integer = 0

        If files.Length > 0 Then
            Do
                Dim fileInfo As System.IO.FileInfo = files(num)
                If (Operators.CompareString(fileInfo.Extension.ToLower, ".exe", False) = 0) Then
                    autorunsCB.Items.Add(fileInfo.Name)
                    exeCollection.Add(fileInfo.FullName.ToString)
                End If
                If (Operators.CompareString(fileInfo.Extension.ToLower, ".love", False) = 0) Then
                    autorunsCB.Items.Add(fileInfo.Name)
                    exeCollection.Add(fileInfo.FullName.ToString)
                End If
                num = num + 1
            Loop While num < CInt(files.Length)
        End If

        Dim directoryInfoArray As DirectoryInfo() = directories
        Dim num1 As Integer = 0
        Do While num1 < CInt(directoryInfoArray.Length)
            getDirectoyExe(directoryInfoArray(num1).FullName)
            num1 = num1 + 1
        Loop
        directories = Nothing
    End Sub

    Private Sub programIconBTN_Click(sender As System.Object, e As System.EventArgs) Handles programiconBTN.Click
        OpenFileDialog1.InitialDirectory = programFolderTB.Text
        OpenFileDialog1.Title = "Select Icon file"
        OpenFileDialog1.FileName = ""
        OpenFileDialog1.RestoreDirectory = True
        OpenFileDialog1.Multiselect = False
        OpenFileDialog1.Filter = "Icon Files (*.ico)|*.ico|All Files (*.*)|*.*"
        OpenFileDialog1.FilterIndex = 1

        If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
            programIconTB.Text = OpenFileDialog1.FileName
            mess("Icon file selected: " & programIconTB.Text)
        Else
            programIconTB.Text = ""
        End If
    End Sub

    Private Sub createExeBT_Click(sender As System.Object, e As System.EventArgs) Handles createExeBT.Click
        On Error Resume Next
        pb.Value = 0

        If programFolderTB.Text.Trim <> "" Then

            If createExeBT.Text = "Cancel" Then
                isCanceled = True
                createExeBT.Text = "Create Exe"
            Else
                isCanceled = False
                createExeBT.Text = "Cancel"
            End If

            If destinationTB.Text.Trim <> "" Then
                If autorunsCB.Items.Count > 0 Then
                    If Not IsNothing(autorunsCB.SelectedItem) Then
                        pb.Value = pb.Value + 1

                        If (Not isCanceled) Then
                            Me.Cursor = Cursors.WaitCursor
                            pb.Value = pb.Value + 1

                            Dim exestr As String = autorunsCB.SelectedItem
                            Dim cmdstr As String = ""

                            If autorunsCB.SelectedItem.ToLower.EndsWith(".love") Then
                                mess("Working with .love file.")
                                exestr = exestr & ".exe"
                                cmdstr = String.Concat("/c copy /b """ & loveFolderTB.Text & "love.exe"" + """ & exeCollection(autorunsCB.SelectedIndex).ToString & """ " & Chr(34) & exestr & Chr(34))
                                MyStartProcess("cmd.exe", cmdstr)
                            Else
                                mess("Working with .exe file.")
                                cmdstr = String.Concat("/c copy /b """ & exeCollection(autorunsCB.SelectedIndex).ToString & """ " & Chr(34) & exestr & Chr(34))
                            End If

                            pb.Value = pb.Value + 1

                            If MyStartProcess("cmd.exe", cmdstr) = True Then
                                mess("Continue process...")

                                File.Delete(destinationTB.Text)
                                File.Delete("config.txt")
                                File.Delete("7zsd.sfx")
                                File.Delete("tmp.7z")

                                pb.Value = pb.Value + 1

                                ' Create Config.txt file 
                                Dim pathArray As String() = Split(destinationTB.Text, "\")
                                Dim nameExe As String = pathArray(pathArray.Length - 1)
                                Dim nameOnly As String = nameExe.Substring(0, nameExe.Length - 4)

                                Dim streamWriter As System.IO.StreamWriter = New System.IO.StreamWriter("config.txt")
                                streamWriter.WriteLine(";!@Install@!UTF-8!")
                                streamWriter.WriteLine(String.Concat("Delete=""%TEMP%\", nameOnly, """"))
                                streamWriter.WriteLine(String.Concat("InstallPath=""%TEMP%\", nameOnly, """"))
                                streamWriter.WriteLine("GUIFlags=""2""")
                                streamWriter.WriteLine("Progress=""No""")
                                streamWriter.WriteLine(String.Concat("RunProgram=""%TEMP%\", nameOnly, "\", nameExe, """"))
                                streamWriter.WriteLine(";!@InstallEnd@!")
                                streamWriter.Close()
                                pb.Value = pb.Value + 1

                                'Create 7z file from folder
                                If MyStartProcess("7z.exe", "a tmp.7z """ & exestr & """ """ & loveFolderTB.Text.Trim & "*""") Then
                                    pb.Value = pb.Value + 1

                                    If (Not isCanceled) Then
                                        'Copy sfx file to use
                                        File.Copy("7zsd.org", "7zsd.sfx")
                                        pb.Value = pb.Value + 1

                                        'Add Icon
                                        If programIconTB.Text.Trim <> "" Then
                                            If Not MyStartProcess("rcedit.exe", String.Concat("/I 7zsd.sfx ", programIconTB.Text)) Then
                                                mess("Add icon file error.")
                                            End If
                                        End If
                                        pb.Value = pb.Value + 1

                                        'Create the new exe
                                        If (Not isCanceled) Then
                                            If MyStartProcess("cmd.exe", String.Concat("/c copy /b 7zsd.sfx + config.txt + tmp.7z """, destinationTB.Text, """")) Then
                                                mess("Process complete.")
                                                pb.Value = pb.Value + 1
                                            Else
                                                mess("Create destination file error.")
                                            End If
                                        Else
                                            mess("Process is canceled.")
                                        End If
                                    Else
                                        mess("Process is canceled.")
                                    End If
                                Else
                                    mess("Create 7z file error.")
                                End If
                            Else
                                mess("Process has error.")
                            End If
                            File.Delete(exestr)
                        Else
                            mess("Process is canceled.")
                        End If
                    Else
                        HighLight(autorunsCB, True)
                        mess("No item is selected.")
                    End If
                Else
                    HighLight(autorunsCB, True)
                    mess("No destination selected.")
                End If
            Else
                mess("No destination selected.")
            End If
        Else
            HighLight(programFolderTB, True)
            mess("Program path not found. Please browse to select program folder.")
        End If

        createExeBT.Text = "Create Exe"
        Me.Cursor = Cursors.Default
        pb.Value = 0

    End Sub

    Public Function MyStartProcess(ByVal program As String, ByVal arguments As String) As Boolean
        mess("Run " & program & " : " & arguments)
        Dim retBool As Boolean
        Try
            Dim process As System.Diagnostics.Process = New System.Diagnostics.Process()
            process.StartInfo.FileName = program
            process.StartInfo.Arguments = arguments
            process.StartInfo.UseShellExecute = False
            process.StartInfo.CreateNoWindow = True
            process.Start()

            While Not process.WaitForExit(250)
                Application.DoEvents()
                If (isCanceled) Then
                    process.Kill()
                End If
            End While

            process.Close()
            retBool = True
        Catch ex As System.Exception
            ProjectData.SetProjectError(ex)
            Interaction.MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Process Error. " & ex.Message)
            ProjectData.ClearProjectError()
        End Try
        Return retBool
    End Function

    Private Sub mess(ByVal message As String)
        ts.Text = message
        logTB.AppendText(message & vbCrLf)
    End Sub

    Private Sub ts_Click(sender As System.Object, e As System.EventArgs) Handles ts.DoubleClick
        If Me.Height < 600 Then
            Me.Height = 608
        Else
            Me.Height = Me.MinimumSize.Height
        End If
    End Sub

    Private Sub destinationBTN_Click(sender As System.Object, e As System.EventArgs) Handles destinationBTN.Click
        SaveFileDialog1.DefaultExt = "exe"
        SaveFileDialog1.OverwritePrompt = False
        SaveFileDialog1.Filter = "exe files (*.exe)|*.exe"
        SaveFileDialog1.RestoreDirectory = True
        SaveFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)

        If (SaveFileDialog1.ShowDialog() = DialogResult.OK) Then
            destinationTB.Text = SaveFileDialog1.FileName
        End If
    End Sub

    Private Sub space_Click(sender As System.Object, e As System.EventArgs) Handles space.Click



        MsgBox(helpText)
    End Sub

    Private Sub TextBox1_TextChanged(sender As System.Object, e As System.EventArgs)

    End Sub
End Class
